package com.example.dinner;


import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dinner.sqlite.DatabaseHelper;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import okhttp3.Call;


public class FragmentList extends Fragment {

    private View mPopView;
    private PopupWindow mPopupWindow;

    ArrayList<String> team = new ArrayList<>();

    SQLiteDatabase db;

    private RecyclerView listRl;
    private MyAdapter myAdapter;
    final int MSG_0x11 = 0x11;//result
    ArrayList arrayList = new ArrayList<ListBeans.ListBean>();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {

                case MSG_0x11:
// fromJson 将json字符串转为bean对象
                    ListBeans listBean = new Gson().fromJson((String) msg.obj, ListBeans.class);
                    arrayList.addAll(listBean.List);
                    myAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    private TextView tv_date;
    String menuId;
    private FloatingActionButton fabDinner;

    ArrayList<String> nameOne = new ArrayList<>();
    ArrayList<String> nameTwo = new ArrayList<>();

    String dinnerName1="";
    String dinnerName2="";

    public ArrayList<String> getNameOne() {
        return nameOne;
    }
    public ArrayList<String> getNameTwo() {
        return nameTwo;
    }

    public void setNameOne(ArrayList<String> nameOne) {
        this.nameOne = nameOne;
    }


    public void setNameTwo(ArrayList<String> nameTwo) {
        this.nameTwo = nameTwo;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        getGroupFromDB();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_list, container, false);
        tv_date = (TextView) view.findViewById(R.id.tv_date);
        listRl = (RecyclerView) view.findViewById(R.id.list_rl);


        fabDinner = (FloatingActionButton) view.findViewById(R.id.fab_dinner);

        myAdapter = new MyAdapter(getContext(), arrayList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());

        listRl.setLayoutManager(layoutManager);

        listRl.setAdapter(myAdapter);

        fabDinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initPopWindow(nameOne,nameTwo);
            }
        });

        return view;
    }

    private void initData(String menuId) {

        OkHttpUtils
                .get()
                .url(API.URL_LIST_ORDER)
                .addParams("menu", menuId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
//                        Message message = Message.obtain();
//                        message.obj = response;   //message.obj=bundle  传值也行
//                        message.what = MSG_0x11;
//                        handler.sendMessage(message);
                        arrayList.clear();
                        ListBeans listBean = new Gson().fromJson(response, ListBeans.class);
                        arrayList.addAll(listBean.List);
                        myAdapter.notifyDataSetChanged();
                        dealData(arrayList);
                    }


                });

    }
    private void dealData(ArrayList<ListBeans.ListBean> arrayList) {

        if (nameOne!=null) {
            nameOne.clear();
        }
        if (nameTwo!=null) {
            nameTwo.clear();
        }
        for (int i = 0; i < arrayList.size(); i++) {
            if (team.contains(arrayList.get(i).getSign())) {
                //这里可以考虑使用sp把菜名先存储下来，再进行比对
                if (arrayList.get(i).getContent().trim().equals(arrayList.get(0).getContent().trim())) {
                    nameOne.add(arrayList.get(i).getSign());
                    dinnerName1=arrayList.get(i).getContent().trim();

                } else {
                    nameTwo.add(arrayList.get(i).getSign());
                    dinnerName2=arrayList.get(i).getContent().trim();
                }
            }
        }
    }
    //
//    public void getSyn(final String url) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    //创建OkHttpClient对象
//                    OkHttpClient client = new OkHttpClient();
//                    //创建Request
//                    Request request = new Request.Builder()
//                            .url(url)//访问连接
//                            .get()
//                            .build();
//                    //创建Call对象
//                    Call call = client.newCall(request);
//                    //通过execute()方法获得请求响应的Response对象
//                    Response response = call.execute();
//                    if (response.isSuccessful()) {
//                        //处理网络请求的响应，处理UI需要在UI线程中处理
//                        //...
//                        Message message = Message.obtain();
//                        message.obj =response.body().string();   //message.obj=bundle  传值也行
//                        message.what = MSG_0x11;
//                        handler.sendMessage(message);
//
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(MessageWrap message) {

        initData(getMenuId(message.message));
    }

    @Override
    public void onResume() {
        super.onResume();

//        initData(menuId);

    }
    private void getGroupFromDB() {
        //依靠DatabaseHelper带全部参数的构造函数创建数据库
        DatabaseHelper dbHelper = new DatabaseHelper(getContext(), "test_db", null, 1);
        db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("user", new String[]{"name"}, null, null, null, null, null);
        //利用游标遍历所有数据对象
        team.clear();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            team.add(name);
        }
    }

    public String getMenuId(String sdata) {
        DinnerBean dinnerBean = new Gson().fromJson(sdata, DinnerBean.class);
        tv_date.setText(dinnerBean.getMenuInfo().getAdd_time());
        menuId = dinnerBean.getMenuInfo().getId();
        int value = Integer.valueOf(menuId);
        if (value % 2 == 0) {
            menuId = String.valueOf(value - 1);//获取之前的记录
            return menuId;

        } else {
            return menuId;
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initPopWindow(ArrayList<String> nameListOne,ArrayList<String> nameListTwo) {
        // TODO Auto-generated method stub
        // 将布局文件转换成View对象，popupview 内容视图
//        mPopView = getLayoutInflater().inflate(R.layout.layout_popup_calendar, null);
        mPopView = getLayoutInflater().inflate(R.layout.layout_popup_name, null);
        // 将转换的View放置到 新建一个popuwindow对象中
        mPopupWindow = new PopupWindow(mPopView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        // 点击popuwindow外让其消失
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x30000000));

        ImageView img_close = (ImageView) mPopView.findViewById(R.id.img_close);


        TextView tvDinnerOne = (TextView) mPopView.findViewById(R.id.tv_dinnerOne);
        RecyclerView rlNameOne = (RecyclerView) mPopView.findViewById(R.id.rl_nameOne);


        TextView tvDinnerTwo = (TextView) mPopView.findViewById(R.id.tv_dinnerTwo);
        RecyclerView rlNameTwo = (RecyclerView)mPopView. findViewById(R.id.rl_nameTwo);

        if (tvDinnerOne!=null) {
            tvDinnerOne.setText(dinnerName1);
        }
        if (tvDinnerTwo!=null) {
            tvDinnerTwo.setText(dinnerName2);
        }


        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
            }
        });

//        ArrayList<TV_MSG> msgArrayList = new ArrayList<>();
//        msgArrayList.add(new TV_MSG("1", Color.RED));
//        msgArrayList.add(new TV_MSG("2", Color.parseColor("#F4B50D")));
//        msgArrayList.add(new TV_MSG("3", Color.YELLOW));
//        msgArrayList.add(new TV_MSG("4", Color.GREEN));
//        msgArrayList.add(new TV_MSG("5", Color.parseColor("#FFFF00")));
//        msgArrayList.add(new TV_MSG("6", Color.BLUE));
//        msgArrayList.add(new TV_MSG("7", Color.parseColor("#9F009A")));
//        msgArrayList.add(new TV_MSG("1", Color.RED));

        //单一布局
        final MyGridViewAdapter adapter = new MyGridViewAdapter(getContext(), nameListOne,2);

        final GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
        rlNameOne.setLayoutManager(layoutManager);

        rlNameOne.setAdapter(adapter);



        final MyGridViewAdapter adapter2 = new MyGridViewAdapter(getContext(), nameListTwo,2);

        final GridLayoutManager layoutManager2 = new GridLayoutManager(getContext(), 4);
        rlNameTwo.setLayoutManager(layoutManager2);

        rlNameTwo.setAdapter(adapter2);


        mPopupWindow.showAtLocation(mPopView, Gravity.CENTER, 0, 0);
    }



}